package net.sahv.bdyz.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import net.sahv.bdyz.model.Admin;
import net.sahv.bdyz.model.AdminRole;
import net.sahv.bdyz.model.Domain;
import net.sahv.bdyz.model.Member;
import net.sahv.bdyz.service.AdminRoleService;
import net.sahv.bdyz.service.AdminService;
import net.sahv.bdyz.service.DomainService;
import net.sahv.bdyz.service.MemberService;
import net.sahv.bdyz.util.PagingUtil;
@Controller
@RequestMapping("admin/memberManage")
public class MemberManageController {

	@Autowired
	private MemberService memberService;
	@Autowired
	private AdminService adminService;
	@Autowired
	private AdminRoleService adminRoleService;// 角色管理员关系
	@Autowired
	private DomainService domainService;
	
	/**
	 * 跳转用户列表
	 * @return
	 * 张羽鹏
	 * 2016年8月8日09:38:52
	 */
	@RequestMapping(value="/memberManageList",method=RequestMethod.GET)
	public String memberManageList(){
		return "admin/memberManage/memberManageList";
	}
	
	/**
	 * 用户列表数据
	 * @param request
	 * @param model
	 * @param pagingUtil
	 * @return
	 * 张羽鹏
	 * 2016年8月8日09:39:36
	 */
	 
	@ResponseBody
	@RequestMapping(value="/memberManageList",method=RequestMethod.POST)
	public JSON memberManageList(HttpServletRequest request,PagingUtil pagingUtil){
		Admin admin = adminService.getCurrent();// 获取当前登录管理员
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		if (admin != null) {
			AdminRole ar = adminRoleService.selectByAid(admin.getaId());
			int roleId = 0;
			if (ar != null) {
				roleId = ar.getrId();
			}

			String mPhone = request.getParameter("M_PHONE");
			String mNickname = request.getParameter("M_NICKNAME");
			String sortField = " ";
			String where = " where 1=1";
			if (roleId == 2) {
				where += " and M_MESSAGE_1=" + admin.getaId();
			}
			if (mNickname != null && !mNickname.equals("")) {
				where += " AND M_NICKNAME LIKE '%" + mNickname + "%'";
			}
			if (mPhone != null && !mPhone.equals("")) {
				where += " AND M_PHONE LIKE '%" + mPhone + "%'";
			}

			param.put("start", pagingUtil.getiDisplayStart());
			param.put("length", pagingUtil.getiDisplayLength());
			param.put("where", where);
			param.put("sortField", sortField);

			List<Map<String, Object>> member = memberService.memberList(param);

			Integer count = memberService.memberListCount(where);

			map.put("aaData", member);
			map.put("iTotalRecords", count);
			map.put("iTotalDisplayRecords", count);
			map.put("sEcho", pagingUtil.getsEcho());
		} else {
			map.put("aaData", "");
			// 查出来总共有多少条记录
			map.put("iTotalRecords", 0);
			map.put("iTotalDisplayRecords", 0);
			map.put("sEcho", pagingUtil.getsEcho());
		}
		return (JSON) JSON.toJSON(map);
	}
	
	/**
	 * 分配专属顾问跳转路径
	 * @param model
	 * @param id
	 * @return
	 * 张羽鹏
	 * 2016年8月8日09:40:04
	 */
	@RequestMapping(value="/memberAdminList",method=RequestMethod.GET)
	public String memberAdminList(Model model,Integer id){
		List<Map<String,Object>> adminSalesmanList=adminService.selectAllSalesman();
		model.addAttribute("id", id);
		model.addAttribute("adminSalesmanList", adminSalesmanList);
		return "admin/memberManage/memberAdminList";
	}
	
	/**
	 * 分配专属顾问
	 * @param adminId
	 * @param mId
	 * @return
	 * 张羽鹏
	 * 2016年8月8日09:41:03
	 */
	@ResponseBody
	@RequestMapping(value="/memberAdmin",method=RequestMethod.POST)
	public ApiResult memberAdmin(Integer adminName,Integer id){
		ApiResult result=new ApiResult();
		Member member =memberService.selectByPrimaryKey(id);
		Admin admin=adminService.selectByPrimaryKey(adminName);
		member.setmMessage1(String.valueOf(adminName));
		member.setmMessage2(admin.getaName());
		int i=memberService.updateByPrimaryKey(member);
		if(i ==1){
			 result.msg.status=0;
			 result.msg.desc="分配成功！";
		}else{
			result.msg.status=1;
			result.msg.desc="分配失败！";
		}
		return result;
	}
	
	/**
	 * 账号停用启用跳转路径
	 * @param model
	 * @param id
	 * @return
	 * 张羽鹏
	 * 2016年8月8日09:41:323
	 */
	@RequestMapping(value="/accountState",method=RequestMethod.GET)
	public String accountState(Model model,Integer id){
		Member member =memberService.selectByPrimaryKeyNew(id);
		model.addAttribute("member", member);
		return "admin/memberManage/accountState";
	}
	
	/**
	 * 账号停用启用
	 * @param state
	 * @param mId
	 * @return
	 * 张羽鹏
	 * 2016年8月8日09:42:00
	 */
	@ResponseBody
	@RequestMapping(value="/accountState",method=RequestMethod.POST)
	public ApiResult accountState(Integer state,Integer mId){
		ApiResult result=new ApiResult();
		Member member =memberService.selectByPrimaryKeyNew(mId);
		member.setmIsDelete(state);
		int i=memberService.updateByPrimaryKey(member);
		if(i ==1){
			 result.msg.status=0;
			 result.msg.desc="设置成功！";
		}else{
			result.msg.status=1;
			result.msg.desc="设置失败！";
		}
		return result;
	}
	
	/**
	 * 查看用户详情
	 * @param model
	 * @param id
	 * @return
	 * 张羽鹏
	 * 2016年8月8日10:17:33
	 */
	@RequestMapping(value="/memberInfo",method=RequestMethod.GET)
	public String memberInfo(Model model,Integer id){
		Member member = memberService.selectByPrimaryKey(id);
		if(member.getmMessage1() == null ){
			member.setmMessage1("未分配");
		}
		if (member.getmProvince() != null) {
			Domain pDomain = domainService.findByCode(member.getmProvince());
			if (pDomain != null) {
				member.setmProvince(pDomain.getdName());
			} else {
				member.setmProvince("");
			}
		}
		// 区县列表
		if (member.getmCity() != null) {
			Domain cDomain = domainService.findByCode(member.getmCity());
			if (cDomain != null) {
				member.setmCity(cDomain.getdName());
			} else {
				member.setmCity("");
			}
		}
		// 区县列表
		if (member.getmArea() != null) {
			Domain aDomain = domainService.findByCode(member.getmArea());
			if (aDomain != null) {
				member.setmArea(aDomain.getdName());
			} else {
				member.setmArea("");
			}
		}
		model.addAttribute("member", member);
		return "admin/memberManage/memberInfo";
	}
	
	/**
	 * 删除用户信息
	 * @param id
	 * @return
	 * 张羽鹏
	 * 2016年8月8日10:21:44
	 */
	@ResponseBody
	@RequestMapping(value="deleteMember",method=RequestMethod.POST)
	public ApiResult deleteConsult(Integer[] id){
		ApiResult result=new ApiResult();
		int j=0;
		for(Integer i:id){
			j=memberService.deleteByPrimaryKey(i);
			if(j==0){
				result.msg.status=1;
				result.msg.desc="删除失败！";
			}
		}
		if(j==1){
			result.msg.status=0;
			result.msg.desc="删除成功！";
		}
		  return result; 
	}
	
	/**
	 * 跳转到用户所在省区统计
	 * @author 张天敏
	 * @date 日期：2016年9月26日 时间：下午2:47:01
	 * @return
	 */
	@RequestMapping(value="memberProvinceList",method=RequestMethod.GET)
	public String memberCount(){
		return "admin/count/memberProvinceList";
	}
	
	/**
	 * 用户所在省区统计
	 * @author 张天敏
	 * @date 日期：2016年9月26日 时间：下午2:47:20
	 * @param request
	 * @param pagingUtil
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/memberProvinceList",method=RequestMethod.POST)
	public JSON memberProvinceList(HttpServletRequest request,PagingUtil pagingUtil){
		Admin admin = adminService.getCurrent();// 获取当前登录管理员
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		if (admin != null) {
			AdminRole ar = adminRoleService.selectByAid(admin.getaId());
			int roleId = 0;
			if (ar != null) {
				roleId = ar.getrId();        //1为管理员，2业务员
			}
			String D_NAME=request.getParameter("D_NAME");
			
			String tableSql=" SELECT d.`D_ID`,d.`D_CODE`,d.`D_NAME`,COUNT(m.`M_ID`) AS MEMBERCOUNT FROM `member` m LEFT JOIN `domain` d ON m.`M_PROVINCE`=d.`D_CODE` ";

			String sortField = " GROUP BY d.`D_CODE` ";
			String where = " where 1=1 AND d.`D_PARENTID`='0' ";
			//查看对应业务员下的用户
			if (roleId == 2) {
				where += " and M_MESSAGE_1=" + admin.getaId();
			}
			
			if(D_NAME!=null&&!D_NAME.trim().equals("")){
				where+=" AND d.`D_NAME` LIKE '%"+D_NAME+"%' ";
			}

			param.put("start", pagingUtil.getiDisplayStart());
			param.put("length", pagingUtil.getiDisplayLength());
			param.put("tableSql", tableSql);
			param.put("where", where);
			param.put("sortField", sortField);
			//用户所在省区列表
			List<Map<String, Object>> memberProvinceList = memberService.memberProvinceList(param);
			//用户所在省区列表统计
			Integer memberProvinceListCount = memberService.memberProvinceListCount(param);

			map.put("aaData", memberProvinceList);
			map.put("iTotalRecords", memberProvinceListCount);
			map.put("iTotalDisplayRecords", memberProvinceListCount);
			map.put("sEcho", pagingUtil.getsEcho());
		} else {
			map.put("aaData", "");
			// 查出来总共有多少条记录
			map.put("iTotalRecords", 0);
			map.put("iTotalDisplayRecords", 0);
			map.put("sEcho", pagingUtil.getsEcho());
		}
		return (JSON) JSON.toJSON(map);
	}
	
	/**
	 * 跳转到用户所在市区统计
	 * @author 张天敏
	 * @date 日期：2016年9月26日 时间：下午4:59:49
	 * @return
	 */
	@RequestMapping(value="memberCityList",method=RequestMethod.GET)
	public String memberCityList(Model model,Integer id){
		model.addAttribute("id", id);
		return "admin/count/memberCityList";
	}
	
	/**
	 * 用户所在市区统计
	 * @author 张天敏
	 * @date 日期：2016年9月26日 时间：下午2:47:20
	 * @param request
	 * @param pagingUtil
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/memberCityList",method=RequestMethod.POST)
	public JSON memberCityList(HttpServletRequest request,PagingUtil pagingUtil){
		Admin admin = adminService.getCurrent();// 获取当前登录管理员
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		if (admin != null) {
			AdminRole ar = adminRoleService.selectByAid(admin.getaId());
			int roleId = 0;
			if (ar != null) {
				roleId = ar.getrId();
			}
			String D_NAME=request.getParameter("D_NAME");
			String id=request.getParameter("id");
			
			String tableSql=" SELECT d.`D_ID`,d.`D_CODE`,d.`D_NAME`,COUNT(m.`M_ID`) AS MEMBERCOUNT FROM `member` m LEFT JOIN `domain` d ON m.`M_CITY`=d.`D_CODE` ";

			String sortField = " GROUP BY d.`D_CODE` ";
			String where = " where 1=1 ";
			
			if(id!=null&&!id.trim().equals("")){
				where+=" AND d.`D_PARENTID`='"+id+"' ";
			}else{
				where+=" AND d.`D_PARENTID`='0' ";
			}
			
			if (roleId == 2) {
				where += " and M_MESSAGE_1=" + admin.getaId();
			}
			
			
			if(D_NAME!=null&&!D_NAME.trim().equals("")){
				where+=" AND d.`D_NAME` LIKE '%"+D_NAME+"%' ";
			}

			param.put("start", pagingUtil.getiDisplayStart());
			param.put("length", pagingUtil.getiDisplayLength());
			param.put("tableSql", tableSql);
			param.put("where", where);
			param.put("sortField", sortField);
			//用户所在省区列表
			List<Map<String, Object>> memberProvinceList = memberService.memberProvinceList(param);
			//用户所在省区列表统计
			Integer memberProvinceListCount = memberService.memberProvinceListCount(param);

			map.put("aaData", memberProvinceList);
			map.put("iTotalRecords", memberProvinceListCount);
			map.put("iTotalDisplayRecords", memberProvinceListCount);
			map.put("sEcho", pagingUtil.getsEcho());
		} else {
			map.put("aaData", "");
			// 查出来总共有多少条记录
			map.put("iTotalRecords", 0);
			map.put("iTotalDisplayRecords", 0);
			map.put("sEcho", pagingUtil.getsEcho());
		}
		return (JSON) JSON.toJSON(map);
	}
	
	/**
	 * 跳转到会员县/区统计
	 * @author 张天敏
	 * @date 日期：2016年9月26日 时间：下午5:36:02
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value="memberAreaList",method=RequestMethod.GET)
	public String memberAreaList(Model model,Integer id){
		model.addAttribute("id", id);
		return "admin/count/memberAreaList";
	}
	
	/**
	 * 会员县/区统计
	 * @author 张天敏
	 * @date 日期：2016年9月26日 时间：下午2:47:20
	 * @param request
	 * @param pagingUtil
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/memberAreaList",method=RequestMethod.POST)
	public JSON memberAreaList(HttpServletRequest request,PagingUtil pagingUtil){
		Admin admin = adminService.getCurrent();// 获取当前登录管理员
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		if (admin != null) {
			AdminRole ar = adminRoleService.selectByAid(admin.getaId());
			int roleId = 0;
			if (ar != null) {
				roleId = ar.getrId();
			}
			String D_NAME=request.getParameter("D_NAME");
			String id=request.getParameter("id");
			
			String tableSql=" SELECT d.`D_ID`,d.`D_CODE`,d.`D_NAME`,COUNT(m.`M_ID`) AS MEMBERCOUNT FROM `member` m LEFT JOIN `domain` d ON m.`M_AREA`=d.`D_CODE` ";

			String sortField = " GROUP BY d.`D_CODE` ";
			String where = " where 1=1 ";
			
			if(id!=null&&!id.trim().equals("")){
				where+=" AND d.`D_PARENTID`='"+id+"' ";
			}else{
				where+=" AND d.`D_PARENTID`='0' ";
			}
			
			if (roleId == 2) {
				where += " and M_MESSAGE_1=" + admin.getaId();
			}
			
			if(D_NAME!=null&&!D_NAME.trim().equals("")){
				where+=" AND d.`D_NAME` LIKE '%"+D_NAME+"%' ";
			}

			param.put("start", pagingUtil.getiDisplayStart());
			param.put("length", pagingUtil.getiDisplayLength());
			param.put("tableSql", tableSql);
			param.put("where", where);
			param.put("sortField", sortField);
			//用户所在省区列表
			List<Map<String, Object>> memberProvinceList = memberService.memberProvinceList(param);
			//用户所在省区列表统计
			Integer memberProvinceListCount = memberService.memberProvinceListCount(param);

			map.put("aaData", memberProvinceList);
			map.put("iTotalRecords", memberProvinceListCount);
			map.put("iTotalDisplayRecords", memberProvinceListCount);
			map.put("sEcho", pagingUtil.getsEcho());
		} else {
			map.put("aaData", "");
			// 查出来总共有多少条记录
			map.put("iTotalRecords", 0);
			map.put("iTotalDisplayRecords", 0);
			map.put("sEcho", pagingUtil.getsEcho());
		}
		return (JSON) JSON.toJSON(map);
	}
	
	
	
}
